"use client";
import { useState } from "react";
import { Suspense } from 'react';
import { useRouter } from 'next/navigation';
import { API_CONFIG } from "../url";

function InvoiceForm() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<'personal' | 'company'>('personal');
  const [loadingTab, setLoadingTab] = useState<null | 'personal' | 'company'>(null);
  const [showModal, setShowModal] = useState(false);
  const [modalMessage, setModalMessage] = useState('');

  const showAlert = (message: string) => {
    setModalMessage(message);
    setShowModal(true);
  };

  const handleTabClick = async (type: 'personal' | 'company') => {
    if (loadingTab === type) return;
    
    try {
      setLoadingTab(type);

      const userId = localStorage.getItem('userId');
      const token = localStorage.getItem('token');
      if (!userId) throw new Error('请先登录！');

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/pay/order/info?stuId=${userId}&paymentStatus=1`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
        }
      );

      const data = await response.json();

      if (response.ok) {
        const hasValidData = data && (data.orderId || (Array.isArray(data) && data.length > 0));

        if (hasValidData) {
          setActiveTab(type);
          router.push(type === 'personal' ? '/invoice/geren' : '/invoice/danwei');
        } else {
          showAlert('请先进行报名缴费');
        }
      } else {
        showAlert('获取订单信息失败，请先完成报名缴费');
      }
    } catch (err) {
      console.error('操作失败:', err);
      showAlert(err instanceof Error ? err.message : '操作失败');
    } finally {
      setLoadingTab(null);
    }
  };

  return (
    <main className="min-h-screen bg-gradient-to-br from-blue-50 to-gray-50">
      {/* 自定义弹窗 */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 max-w-md w-full mx-4 shadow-2xl animate-fade-in">
            <div className="text-center">
              <h3 className="text-xl font-semibold text-gray-800 mb-4">{modalMessage}</h3>
              <button
                onClick={() => setShowModal(false)}
                className="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}

      <section className="py-16 pt-12">
        <div className="container mx-auto px-4">
          <div className="max-w-4xl mx-auto">
            <div className="bg-white rounded-2xl shadow-xl p-10 border border-gray-100 transition-all hover:shadow-2xl">
              <div className="text-center mb-12">
                <h2 className="text-4xl font-bold text-gray-800 mb-2">发票开具信息</h2>
                <p className="text-lg text-gray-500">请选择您的开票类型</p>
              </div>

              <div className="flex justify-center gap-8 mb-12">
                <button
                  onClick={() => handleTabClick('personal')}
                  className={`relative px-12 py-5 text-xl font-semibold transition-all duration-300 rounded-xl ${activeTab === 'personal'
                      ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg transform hover:scale-105'
                      : 'bg-white text-gray-700 border-2 border-gray-200 hover:border-blue-300 shadow-md hover:shadow-lg'
                    } ${loadingTab === 'personal' ? 'opacity-70 cursor-not-allowed' : ''}`}
                >
                  {loadingTab === 'personal' ? (
                    <div className="flex items-center justify-center gap-2">
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      <span>处理中...</span>
                    </div>
                  ) : (
                    <>
                      个人开票
                      {activeTab === 'personal' && (
                        <span className="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-4 h-4 bg-blue-600 rotate-45"></span>
                      )}
                    </>
                  )}
                </button>

                <button
                  onClick={() => handleTabClick('company')}
                  className={`relative px-12 py-5 text-xl font-semibold transition-all duration-300 rounded-xl ${activeTab === 'company'
                      ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg transform hover:scale-105'
                      : 'bg-white text-gray-700 border-2 border-gray-200 hover:border-blue-300 shadow-md hover:shadow-lg'
                    } ${loadingTab === 'company' ? 'opacity-70 cursor-not-allowed' : ''}`}
                >
                  {loadingTab === 'company' ? (
                    <div className="flex items-center justify-center gap-2">
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      <span>处理中...</span>
                    </div>
                  ) : (
                    <>
                      单位开票
                      {activeTab === 'company' && (
                        <span className="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-4 h-4 bg-blue-600 rotate-45"></span>
                      )}
                    </>
                  )}
                </button>
              </div>

              <div className="bg-gray-50 rounded-xl p-8 border border-gray-200">
                {activeTab === 'personal' ? (
                  <div className="text-center">
                    <h3 className="text-2xl font-semibold text-gray-800 mb-6">点击按钮跳转到个人开票页面</h3>
                  </div>
                ) : (
                  <div className="text-center">
                    <h3 className="text-2xl font-semibold text-gray-800 mb-6">正在跳转到单位开票页面...</h3>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

export default function CertificatesPage() {
  return (
    <Suspense fallback={
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
    }>
      <InvoiceForm />
    </Suspense>
  );
}